﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Interactivity;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Input;
using System.Windows;
using XWord.WPF.ApplicationFramework.Extensions;
using System.Windows.Data;
using XWord.WPF.ApplicationFramework.Threads;
namespace XWord.WPF.Behaviors
{
    public class ScrollViewerTipBehavior : Behavior<ItemsControl>
    {
        protected override void OnAttached()
        {
            tip = new ToolTip();
            tip.HasDropShadow = false;
            tip.Placement = PlacementMode.Left;
            tip.MinWidth = 100;
            AssociatedObject.PreviewMouseLeftButtonDown += new MouseButtonEventHandler(AssociatedObject_PreviewMouseLeftButtonDown);
            AssociatedObject.PreviewMouseLeftButtonUp += new MouseButtonEventHandler(AssociatedObject_PreviewMouseLeftButtonUp);
            AssociatedObject.AddHandler(ScrollViewer.ScrollChangedEvent, new ScrollChangedEventHandler(ScrollChanged));
            base.OnAttached();
        }

        private void ScrollChanged(object sender, ScrollChangedEventArgs e)
        {
            if (!AssociatedObject.HasItems || (AssociatedObject.HasItems && AssociatedObject.Items.Count < e.VerticalOffset)) return;
            UIThread.BeginInvoke(() => {
                var item = AssociatedObject.ItemContainerGenerator.ContainerFromIndex(Convert.ToInt32(e.VerticalOffset)) as FrameworkElement;
                var count = Convert.ToInt32(AssociatedObject.ActualHeight / item.ActualHeight);
                var displayItem = Convert.ToInt32((e.VerticalOffset + Math.Ceiling(e.VerticalOffset * (count - 2) / (AssociatedObject.Items.Count - count + 1))));
                tip.SetBinding(ToolTip.ContentProperty, new Binding(ItemPath) { Source = AssociatedObject.Items[displayItem] });
            });
        }

        public string ItemPath { get; set; }

        void AssociatedObject_PreviewMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            tip.IsOpen = false;
            tip.PlacementTarget = null;
        }

        void AssociatedObject_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            var element = e.OriginalSource as FrameworkElement;

            if (element.FindAncestor<ScrollBar>() == null) return;
            if (tip.PlacementTarget == null)
            {
                tip.PlacementTarget = element;
                tip.IsOpen = true;
            }
        }

        private double itemHeight;
        private ToolTip tip;
    }
}
